package com.ezlcp.form.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ezlcp.commons.base.entity.IUser;
import com.ezlcp.commons.utils.ContextUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Elwin ZHANG
 * @description: 自定义自动填充通用字段<br />
 * @date 2022/5/11 17:11
 */
@Component
public class DbMetaObjectHandler implements MetaObjectHandler {
    private final static String UPDATE_TIME = "updateTime";
    private final static String CREATE_TIME = "createTime";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_BY = "updateBy";
    private final static String TENANT_ID = "tenantId";

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(CREATE_TIME, metaObject);
        Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
        if (createTime == null || updateTime == null) {
            Date date = new Date();
            if (createTime == null) {
                setFieldValByName(CREATE_TIME, date, metaObject);
            }
        }
        IUser user = ContextUtil.getCurrentUser();
        Object createBy = getFieldValByName(CREATE_BY, metaObject);
        if (createBy == null && user != null) {
            setFieldValByName(CREATE_BY, user.getAccount(), metaObject);
        }
        /**
         * 租户ID
         */
        Object tenantId = getFieldValByName(TENANT_ID, metaObject);
        if (tenantId == null && user != null) {
            setFieldValByName(TENANT_ID, user.getTenantId(), metaObject);
        }

    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //mybatis-plus版本2.0.9+
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        IUser user = ContextUtil.getCurrentUser();
        if (ObjectUtil.isNotEmpty(user)) {
            setFieldValByName(UPDATE_BY, user.getAccount(), metaObject);
        }
    }
}
